<?php
// +----------------------------------------------------------------------
// | EpisodeAllocation 类型服务
// +----------------------------------------------------------------------
// | 主要服务于EpisodeAllocation数据处理
// +----------------------------------------------------------------------
// | 错误编码头 208xxx
// +----------------------------------------------------------------------

namespace app\service;


use app\tool\SingletonTrait;

class EpisodeAllocationService
{

    // 单例工具
    use SingletonTrait;

    /**
     * 组织剧集场次查询sql
     * "initial_episode_code_list": [
     *    {
     *           "initial_episode_code": "EP012",
     *           "showings_number": [
     *           "SC001",
     *           "SC002",
     *           "SC002",
     *           "SC003"
     *           ]
     *    },
     *    {
     *           "initial_episode_code": "EP013",
     *           "showings_number": [
     *           "SC001"
     *           ]
     *     }
     *  ]
     * @param $initialEpisodeCodeList
     * @param $episodeKey
     * @param $showingsKey
     * @return string
     */
    public function getEpisodeShowingsSql($initialEpisodeCodeList, $episodeKey, $showingsKey): string
    {
        if (empty($episodeKey) || empty($showingsKey)) {
            return '';
        }
        $sql = '(';
        foreach ($initialEpisodeCodeList as $item) {
            $sql .= "(`$episodeKey` = " . "'{$item[$episodeKey]}' ";
            $showingsNumberSql = '';
            if (!empty($item[$showingsKey])) {
                foreach ($item[$showingsKey] as $showingsNum) {
                    $showingsNumberSql .= "'" . $showingsNum . "',";
                }
                $showingsNumberSql = trim($showingsNumberSql, ',');
                $showingsNumberSql = "and `$showingsKey` IN ({$showingsNumberSql})";
                $sql .= $showingsNumberSql;
            }
            $sql .= ' ) or ';
        }
        $sql = trim($sql, 'or ');
        $sql .= ')';
        return $sql;
    }

}
